class FlyBookNotice {
    constructor(object, config) {
        this.targetUrl = config.target.host;
        this.sourceUrl = config.source.host;
        this.url = config.flybook.url;
        let preg = new RegExp(/localhost/);
        let isLocal = preg.test(this.targetUrl);
        if (isLocal) {
            this.targetUrl = this.composeUrlFromParams(this.targetUrl);
        }

        this.payload = this.readyPayload(object);
    }

    readyPayload(object)
    {
        let ticketObject = object.ticket;
        let region = object.newValues.fields.customfield_14800[0]?.value;
        const priority = window.document.querySelector('#priority-val').textContent.trim();

        return {
            "hp_jira_key": object.parentTicketId,
            "hp_jira_url": this.getRightUrl(this.sourceUrl + "/browse/" + object.parentTicketId),
            "hp_jira_title": priority + " - " + ticketObject.fields.summary.replace(/urgent/gi, ''),
            "st_jira_key": ticketObject.key,
            "st_jira_url": this.getRightUrl(this.targetUrl + "/browse/" + ticketObject.key),
            "st_jira_title": "ST JIRA",
            "region": region,
            "assignee": {
                "displayName": ticketObject.fields.assignee.displayName,
                "emailAddress": ticketObject.fields.assignee.emailAddress
            }
        };
    }

    send() {
        console.log('### send playload', this.payload);
        fetch(this.url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(this.payload)
        })
       .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
       .then(data => console.log('## Success:', data))
       .catch(error => console.error('Error:', error));
    }

    composeUrlFromParams(inputUrl) {
        try {
            // 创建URL对象解析输入(自动处理编码问题)
            const urlObj = new URL(inputUrl);
            const params = new URLSearchParams(urlObj.search);
            
            // 参数存在性校验
            if (!params.has('host')) {
                console.warn('URL中缺少host参数');
                return null;
            }

            // 获取并解码参数值
            const host = decodeURIComponent(params.get('host'));
            let uri = '';
            if (params.has('uri')) {
                uri = decodeURIComponent(params.get('uri'));
            }
            
            // 规范化URI格式(确保以/开头)
            const normalizedUri = uri.startsWith('/') ? uri : `/${uri}`;
            
            // 验证host格式
            if (!/^https?:\/\//i.test(host)) {
                throw new Error('host参数必须包含协议头(http/https)');
            }
            
            // 组成新URL并验证有效性
            const newUrl = new URL(normalizedUri, host).href;
            return newUrl;
        } catch (e) {
            console.error('URL处理错误:', e.message);
            return null;
        }
    }

    getRightUrl($url)
    {
        let urlObj = new URL($url);
        let pathname = urlObj.pathname.replace(/\/\//g, '/');
        return urlObj. origin + pathname + urlObj.search;
    }
}